<template>
  <div>
    <div class="button-group">
      <el-button type="primary" @click="handleAdd">添加馆区</el-button>
      <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table
        :data="libraryAreas"
        style="width: 100%"
        border
        :height="750"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="areaCodeId" label="区号" width="180"></el-table-column>
      <el-table-column prop="bookLibrary" label="馆区位置" width="180"></el-table-column>
      <el-table-column prop="areaName" label="馆区名"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑馆区对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="areaForm">
        <el-form-item label="图书馆位置" prop="bookLibrary">
          <el-input v-model="form.bookLibrary"></el-input>
        </el-form-item>
        <el-form-item label="馆区名" prop="areaName">
          <el-input v-model="form.areaName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import http from '../utils/axios';

// 表格数据
const libraryAreas = ref([]);

// 表单引用
const areaForm = ref(null);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加馆区');
const form = reactive({
  areaCodeId: null,
  bookLibrary: '',
  areaName: ''
});

const rules = {
  bookLibrary: [
    {required: true, message: '请输入图书馆位置', trigger: 'blur'}
  ],
  areaName: [
    {required: true, message: '请输入馆区名', trigger: 'blur'}
  ]
};

const selectedRows = ref([]);
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个馆区吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.areaCodeId);
    const deletePromises = ids.map(id => http.delete(`/Area/delete/${id}`));
    Promise.allSettled(deletePromises).then(results => {
      results.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          ElMessage.success(`删除成功: 区号 ${ids[index]}`);
        } else {
          // 提取具体的错误信息
          const errorMessage = result.reason.response?.data?.data || '删除失败';
          ElMessage.error(`删除失败: 区号 ${ids[index]} ${errorMessage}`);
        }
      });
      fetchLibraryAreas();
      selectedRows.value = []; // 清空选中项
    }).catch(error => {
      ElMessage.error('删除操作失败', error);
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};


// 获取所有馆区
const fetchLibraryAreas = async () => {
  try {
    const response = await http.get('/Area/all');
    libraryAreas.value = response.data;
  } catch (error) {
    ElMessage.error('获取馆区列表失败');
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    await areaForm.value.validate();

    try {
      if (form.areaCodeId) {
        // 更新馆区
        await http.put(`/Area/update/${form.areaCodeId}`, form);
        ElMessage.success('更新馆区成功');
      } else {
        // 添加馆区
        await http.post('/Area/save', form);
        ElMessage.success('添加馆区成功');
      }
      dialogVisible.value = false;
      await fetchLibraryAreas();
      areaForm.value.resetFields(); // 重置表单
    } catch (error) {
      ElMessage.error('操作失败');
    }
  } catch (validationError) {
    // 验证失败会自动显示错误信息
    return false;
  }
};

// 添加馆区
const handleAdd = () => {
  dialogTitle.value = '添加馆区';
  form.areaCodeId = null;
  form.bookLibrary = '';
  form.areaName = '';
  dialogVisible.value = true;
};

// 编辑馆区
const handleEdit = (index, row) => {
  dialogTitle.value = '编辑馆区';
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 初始化数据
onMounted(() => {
  fetchLibraryAreas();
});
</script>

<style scoped>
.button-group {
  margin-bottom: 15px;
}

.button-group .el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}
</style>